/**
 * 数据表格处理  dukai.js 更新版
 * 基于layui 2.6.8
 * @author sudukai
 * @date 2022-3-14
 * @version 1.0.4
 **/
layui.define(['layer', 'form', 'table', 'laytpl', 'element'], function (exports) {
    var MOD_NAME = 'kaige', $ = layui.jquery, form = layui.form, table = layui.table, layer = layui.layer, laytpl = layui.laytpl, element = layui.element;
    kaige = function () { };
    kaige.prototype.config = function () {
        return {
            form: {
                opentype: 'layer.open', // layer.open | dom 传入接收的ID
                data: {},
                area: ['700px', '420px'],
                offset: 'auto',
                title: false,
                maxmin: false,
                overflow: true, //默认开启
                callbefore: function () { }, //窗体成功打开后处理回调，在监听表单前
                callback: function (res) { },//表单提交后回调
                postbefore: function (d) {
                    //提交前表单处理回调，改变表单上传值
                    return d;
                },
            },
            del: {
                callback: function (res) { },
            },
            viewimage: {
                maxwidth: '500px',
                maxheight: '500px',
            },
            table: {
                height: 'full-30',
                defaultToolbar: ['filter'],
                page: {
                    layout: ['prev', 'page', 'next', 'limit', 'count', 'skip', 'refresh'],
                    groups: 8,
                    limits: [20, 50, 100, 150, 200, 300, 500, 1000]
                },
                limit: '20',
                method: 'GET',
                // nosign: false, //是否不要签名（默认是签名的）,true=不要签
                done: function (res, curr, count) { }
            },
            xmSelect: {
                theme: {
                    color: '#0081ff',
                },
                filterable: true
            }
        };
    }

    /**新增或编辑，通用处理方法 tpl*/
    kaige.prototype.form = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                laytpl(content).render(res.data, function (reshtml) {
                    if (e.opentype == 'layer.open') {
                        layer.open({
                            id: e.id + '_form_box',
                            type: 1,
                            anim: 4,
                            area: e.area,
                            title: e.title,
                            maxmin: e.maxmin,
                            offset: e.offset,
                            content: reshtml,
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                $('#' + e.id + '_form_btn_save').click();
                            },
                            success: function (layero, index) {
                                if (e.overflow === true) $('#' + e.id + '_form_box').css('overflow', 'visible');
                                (typeof e.callbefore === 'function') && e.callbefore(layero, index);
                                (typeof e.getdata === 'function') && e.getdata(res);
                                form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                                //固定提交按钮 id + _form_btn_save
                                form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                                    if (typeof e.postbefore === 'function') {
                                        data.field = e.postbefore(data.field);
                                    }
                                    if (data.field === false) return false;
                                    $.ajax({
                                        type: 'POST',
                                        encode: e.encode ? e.encode : 0,
                                        url: e.url,
                                        data: data.field,
                                        success: function (res2) {
                                            if (res2.status) {
                                                layer.msg(res2.msg, { time: 1300 }, function () {
                                                    if (e.tablelayid) table.reload(e.tablelayid);
                                                    layer.close(index);
                                                });
                                            } else {
                                                layer.msg(res2.msg);
                                            }
                                            (typeof e.callback === 'function') && e.callback(res2);
                                        }
                                    });
                                    return false;
                                });
                            }
                        });
                    } else if (e.opentype == 'dom') {
                        $('#' + e.box).html(reshtml);
                        (typeof e.callbefore === 'function') && e.callbefore();
                        (typeof e.getdata === 'function') && e.getdata(res);
                        form.render(null, e.id + '_form_lay_filter');
                        form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                            if (typeof e.postbefore === 'function') {
                                data.field = e.postbefore(data.field);
                            }
                            if (data.field === false) return false;
                            $.ajax({
                                type: 'POST',
                                encode: e.encode ? e.encode : 0,
                                url: e.url,
                                data: data.field,
                                success: function (res2) {
                                    if (res2.status) {
                                        layer.msg(res2.msg, { time: 1300 }, function () {
                                            if (e.tablelayid) table.reload(e.tablelayid);
                                        });
                                    } else {
                                        layer.msg(res2.msg);
                                    }
                                    (typeof e.callback === 'function') && e.callback(res2);
                                }
                            });
                            return false;
                        });
                    }
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**查看，通用处理方法 tpl，默认配置与form 一致*/
    kaige.prototype.details = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                laytpl(content).render(res.data, function (reshtml) {
                    if (e.opentype == 'layer.open') {
                        layer.open({
                            id: e.id + '_form_box',
                            type: 1,
                            anim: 4,
                            area: e.area,
                            title: e.title,
                            maxmin: e.maxmin,
                            content: reshtml,
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                layer.close(index);
                            },
                            success: function (layero, index) {
                                if (e.overflow) $('#' + e.id + '_form_box').css('overflow', 'visible');
                                (typeof e.callbefore === 'function') && e.callbefore(layero, index);
                                (typeof e.getdata === 'function') && e.getdata(res);
                                form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                                // 查看是没有再提交的，有需要直接写在 callback;
                                (typeof e.callback === 'function') && e.callback(layero, index); // 这里传出 layer.open 的对象与窗口索引
                            }
                        });
                    } else if (e.opentype == 'dom') {
                        $('#' + e.box).html(reshtml);
                        (typeof e.callbefore === 'function') && e.callbefore();
                        (typeof e.getdata === 'function') && e.getdata(res);
                        form.render(null, e.id + '_form_lay_filter');
                        (typeof e.callback === 'function') && e.callback();
                    }
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**删除，支持批量删除 */
    kaige.prototype.del = function (e) {
        var t = this;
        e = $.extend(t.config().del, e);
        var data = e.data;
        if (data.length <= 0) {
            layer.msg("请先选要操作的数据！");
            return t;
        }
        var ids = '';
        $.each(data, function (i, obj) {
            ids += obj.id + ',';
        });
        ids = ids.substring(0, ids.length - 1);
        layer.confirm('确认删除选中的数据吗？', {
            title: '<i class="layui-icon layui-icon-delete"></i> 删除确认',
            btn: ['确认', '取消']
        }, function () {
            $.post(e.url, { id: ids }, function (res) {
                res.status && (e.tablelayid && table.reload(e.tablelayid, {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                }));
                layer.msg(res.msg);
                (typeof e.callback === 'function') && e.callback(res);
            });
        });
        return t;
    }

    /**查看图片 */
    kaige.prototype.viewimage = function (e) {
        var t = this;
        e = $.extend(t.config().viewimage, e);
        if (e.url == undefined || e.url == '' || e.url == null) return t;
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            scrollbar: false,
            maxWidth: e.maxwidth,
            maxHeight: e.maxheight,
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: "<img style='max-width:" + e.maxwidth + "px;max-height:" + e.maxheight + "px;' src='" + e.url + "' alt=''>",
        });
        return t;
    }

    /**
     * 上传文件P2P交互(赋值)
     * @后台得到 id,name,url,ext,type
     */
    kaige.prototype.file_info = function (d) {
        if (d) {
            var src = d.url ? d.url : (d.src ? d.src : '');
            $(d.inputid).val(d.id);
            $(d.imgid).attr('src', src);
            layer.close(window.file_win_layid);
        }
    }

    /**表单里多个字段需要上传文件的 */
    kaige.prototype.upload_multi_files = function (d) {
        if (d) {
            $(d.btn).on('click', function (ev) {
                window.file_win_layid = layer.open({
                    type: 2,
                    title: '<i class="fa fa-upload"></i> 上传文件',
                    shade: 0.5,
                    area: ['90%', '90%'],
                    content: d.url,
                    success: function (layero, index) {
                        // 交互方法，如有自定义就使用自定义的，如果没有就使用默认的
                        if (typeof d.file_info === 'function') {
                            d.file_info();
                        } else {
                            window.file_info = function (opt) {
                                if (opt) {
                                    var src = opt.url ? opt.url : (opt.src ? opt.src : '');
                                    kaige.file_info({
                                        inputid: d.input_id,
                                        imgid: d.img_id,
                                        id: opt.id,
                                        url: src
                                    });
                                }
                            };
                        }
                        //回调
                        if (typeof d.callback === 'function') {
                            d.callback();
                        }
                    }
                });
            });
        }
    }

    /**加载表格列表 */
    kaige.prototype.table = function (e) {
        var t = this;
        e = $.extend(t.config().table, e);
        table.render(e);
    }

    /**
     * 选择框 页面需要 加载 xmSelect.js
     * @param {*} e 
     */
    kaige.prototype.xmSelect = function (e) {
        if (typeof (xmSelect) !== 'object') {
            layer.msg('未加载xmSelect.js');
            return false;
        }
        var t = this;
        e = $.extend(t.config().xmSelect, e);
        //dom名称关系不能乱.
        var input_elm = '#' + e.id;
        var select_elm = input_elm + '_select_box';
        var input_name_elm = input_elm + '_name';
        var obj = $(input_elm), in_obj = $(input_name_elm);
        setTimeout(function () {
            var xsopt = {
                el: select_elm,
                theme: e.theme,
                filterable: e.filterable,
                data: [],
                radio: e.radio || false,
                clickClose: e.clickClose || false,
                on: function (data) {
                    var id = '', name = '';
                    if (e.radio) {
                        id = (data.arr)[0].value;
                        name = (data.arr)[0].name;
                    } else {
                        layui.each(data.arr, function (index, item) {
                            if (index > 0) {
                                id += ',', name += ',';
                            }
                            id += item.value;
                            name += item.name;
                        });
                    }
                    obj.val(id);
                    in_obj.val(name);
                },
            };
            if (typeof (e.model) === 'object') {
                xsopt.model = e.model;
            } else {
                if (e.radio === true) {
                    xsopt.model = {
                        label: {
                            type: 'text',
                            text: {
                                //左边拼接的字符
                                left: '',
                                //右边拼接的字符
                                right: '',
                                //中间的分隔符
                                separator: ', ',
                            },
                        }
                    };
                }
            }
            if (e.disabled === true) {
                xsopt.disabled = e.disabled;
            }

            var xmdom = xmSelect.render(xsopt);
            var old_value = obj.val();
            $.ajax({
                type: 'GET',
                async: false, // 异步方可同页面多次使用
                url: e.url,
                data: e.udata || {},
                success: function (res) {
                    // 处理 数据格式
                    if (res.code == 0) {
                        var data = [];
                        layui.each(res.data, function (index, item) {
                            data.push({
                                'name': (item.name ? item.name : item.real_name),
                                'value': item.id,
                                'selected': strIn(item.id.toString(), old_value)
                            });
                        });
                        xmdom.update({ data: data, autoRow: true, });
                    }
                }
            });
        }, 200);
    }

    /**流程专用表单*/
    kaige.prototype.flowform = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                var lodata = res.data;
                laytpl(content).render(lodata, function (reshtml) {
                    var lo = {
                        id: e.id + '_form_box',
                        type: 1,
                        anim: 2,
                        area: e.area,
                        title: e.title,
                        maxmin: !e.maxmin,
                        shade: e.shade || 0.5,
                        offset: e.offset,
                        content: reshtml,
                        btn: ['保存并提交', '保存为草稿', '取消'],
                        yes: function (index, layero) {
                            $('#kaige_is_put').val(1); //为1 直接提交流程
                            $('#' + e.id + '_form_btn_save').click();
                        },
                        btn2: function (index, layero) {
                            $('#kaige_is_put').val(2); //草稿
                            $('#' + e.id + '_form_btn_save').click();
                            return false;
                        },
                        success: function (layero, index) {
                            layero.find('.layui-layer-min').remove(); //去掉最小化按钮
                            // layero.find('.layui-layer-max').remove(); //去掉最大化按钮
                            if (e.overflow === true) $('#' + e.id + '_form_box').css('overflow', 'visible');
                            (typeof e.callbefore === 'function') && e.callbefore(layero, index);
                            (typeof e.getdata === 'function') && e.getdata(res);
                            form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                            //固定提交按钮 id + _form_btn_save
                            form.on('submit(' + e.id + '_form_btn_save' + ')', function (data) {
                                if (typeof e.postbefore === 'function') {
                                    data.field = e.postbefore(data.field);
                                }
                                if (data.field === false) return false;
                                $.ajax({
                                    type: 'POST',
                                    encode: e.encode ? e.encode : 0,
                                    url: e.url,
                                    data: data.field,
                                    success: function (res2) {
                                        if (res2.status) {
                                            layer.msg(res2.msg, { time: 1300 }, function () {
                                                if (e.tablelayid) table.reload(e.tablelayid);
                                                layer.close(index);
                                            });
                                        } else {
                                            layer.msg(res2.msg);
                                        }
                                        (typeof e.callback === 'function') && e.callback(res2);
                                    }
                                });
                                return false;
                            });
                        }
                    };
                    // 已经提交 不能再编辑，但可以撤回
                    if (typeof (lodata.is_put) === 'number' && lodata.is_put == 1 && typeof (lodata.status) === 'number' && lodata.status == 1) {
                        lo.btn = ['撤回', '取消'];
                        lo.yes = function (index, layero) {
                            $('#kaige_is_put').val(3); //1已提交2未提交3撤回
                            $('#' + e.id + '_form_btn_save').click();
                        };
                        delete lo.btn2;
                    }
                    if (typeof (lodata.status) === 'number' && lodata.status > 1) {
                        delete lo.btn;
                        delete lo.yes;
                        delete lo.btn2;
                    }
                    layer.open(lo);
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    /**流程查看专用*/
    kaige.prototype.flowview = function (e) {
        var t = this;
        e = $.extend(t.config().form, e);
        if (e.id == undefined || $('#' + e.id + "_form_html").length < 1) {
            layer.msg('缺少模板');
            return false;
        }
        $.get(e.url, e.data, function (res) {
            if (res.status) {
                if (typeof (res.data) !== 'object') {
                    layer.msg('接口数据错误');
                    return false;
                }
                var content = $('#' + e.id + "_form_html").html();
                laytpl(content).render(res.data, function (reshtml) {
                    layer.open({
                        id: e.id + '_form_box',
                        type: 1,
                        anim: 2,
                        area: e.area,
                        title: e.title,
                        maxmin: !e.maxmin,
                        content: reshtml,
                        success: function (layero, index) {
                            layero.find('.layui-layer-min').remove(); //去掉最小化按钮
                            if (e.overflow) $('#' + e.id + '_form_box').css('overflow', 'visible');
                            (typeof e.callbefore === 'function') && e.callbefore(layero, index);
                            (typeof e.getdata === 'function') && e.getdata(res);
                            form.render(null, e.id + '_form_lay_filter');//固度表单 id名 + '_form_lay_filter'
                            // 查看是没有再提交的，有需要直接写在 callback;
                            (typeof e.callback === 'function') && e.callback(layero, index); // 这里传出 layer.open 的对象与窗口索引
                        }
                    });
                });
            } else {
                layer.msg(res.msg);
                return false;
            }
        });
        return t;
    };

    var kaige = new kaige();
    exports(MOD_NAME, kaige)
});